const db = require("../../../db");
const { NULL_ERROR, SYSTEM_ERROR } = require("../../../utils/errorCode");

exports.main = async (req, res) => {
    console.log(req.body);
    let { productList, totalPrice, totalNum, address, paymentType, phone, consigneeName } = req.body;
    const { userId } = req.auth;
    // todo 判断数据
    if (!productList || !totalPrice || !totalNum || !address || !paymentType) {
        return res.err(NULL_ERROR);
    }
    // 增加订单信息
    const data = {
        totalPrice,
        totalNum,
        address,
        userId,
        paymentType,
        phone,
        consigneeName
    }
    const addOrderSql = `insert into orders set ?`;
    await db.query(addOrderSql, data, async (err, result) => {
        if (err) {
            console.log(err);
            return res.err(SYSTEM_ERROR);
        }
        productList = JSON.parse(productList);
        // 增加商品同时减少库存
        const addOrderDetailSql = `insert into order_detail set ?;
                                    update products set productInventory = productInventory - ? where productId = ?`;
        for (const item of productList) {
            let productDetail = {
                orderId: result.insertId,
                productId: item.productId,
                num: item.num,
                productPrice: item.productPrice
            }

            await db.query(addOrderDetailSql, [productDetail, item.num, item.productId], (err, result) => {
                if (err) {
                    console.log(err);
                    return res.err(SYSTEM_ERROR);
                }
            })
        }

        return res.sid(result.insertId);
    })


}
